package base;

import java.awt.geom.Point2D;
import java.util.Random;


public class DamageModel {
	private static final Random gen = new Random();
	
	public static double rollDamage(Ship attacker, Ship target, int turretID)
	{
		if (turretID >= attacker.getNumTurrets()) {
			return Double.NaN;
		}
		
		Turret turret = attacker.getTurret(turretID);
		
		return DamageModel.rollDamage(turret, turret.getPos(), target, target.getPos());
	}
	
	public static double rollDamage(Turret attackingTurret, Point2D.Double turretPos, Ship target, Point2D.Double targetPos)
	{
		double chance = DamageModel.getChance(attackingTurret, turretPos, target, targetPos);
		double baseDamage = attackingTurret.getBaseDamage();
		
		double roll = gen.nextDouble();
		if (roll > chance)
		{
			return 0;
		}
		
		return (roll + 0.5) * baseDamage;
	}
	
	public static double getChance(Turret attackingTurret, Point2D.Double turretPos, Ship target, Point2D.Double targetPos)
	{
		double rangeSq = turretPos.distanceSq(targetPos);
		double optimal = attackingTurret.getOptimal();
		double falloff = attackingTurret.getFalloff();
		
		double rangeTerm;
		if (falloff <= 0 || rangeSq <= optimal * optimal)
		{
			rangeTerm = 0;
		}
		else
		{
			double range = Math.sqrt(rangeSq);
			rangeTerm = Math.pow((range - optimal)/falloff, 2);
		}
		
		double transversal = DamageModel.getTransversal(attackingTurret.getShip(), target);
		double turretSignature = attackingTurret.getSignatureRadius();
		double targetSignature = 0; /*target.getSignatureRadius();*/
		double turretTracking = attackingTurret.getTracking();
		double transversalSq = transversal * transversal;
		double turretSignatureSq = turretSignature * turretSignature;
		double targetSignatureSq = targetSignature * targetSignature;
		double turretTrackingSq = turretTracking * turretTracking;
		
		double trackingTerm;
		if (turretTracking == 0 || rangeSq == 0 || targetSignature == 0)
		{
			trackingTerm = 0;
		}
		else
		{
			trackingTerm = transversalSq * turretSignatureSq / (rangeSq * turretTrackingSq * targetSignatureSq);
		}
		
		return Math.pow(0.5, trackingTerm + rangeTerm);
	}
	
	public static double getTransversal(Ship a, Ship b)
	{
		// TODO
		// hae molempien laivojen nopeus vektoreina, hae nopeuksien erotusvektori, 
		return 0.0;
	}
	
	public static double expectedDamage(Turret attackingTurret, Point2D.Double turretPos, Ship target, Point2D.Double targetPos)
	{
		return attackingTurret.getBaseDamage();
	}

}
